package xiaojian.toolkit.management;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.util.ExceptionUtils;

public class DefaultServerFacade {
	private static final Logger LOG = LoggerFactory
			.getLogger(DefaultServerFacade.class);
	private final String _filename;

	public DefaultServerFacade(String fname) {
		this._filename = fname;
	}

	public String getVersion() {
		return "0.0.1";
	}

	public String getServerId() {
		File idfile = new File(this._filename);
		if (!idfile.exists()) {
			UUID id = UUID.randomUUID();

			OutputStream os = null;
			try {
				os = new FileOutputStream(idfile);

				IOUtils.write(id.toString(), os, "UTF-8");

				return id.toString();
			} catch (Exception e) {
				LOG.error(
						"exception when write uuid {} to {}, detail: {}",
						new Object[] { id, this._filename,
								ExceptionUtils.exception2detail(e) });
			} finally {
				IOUtils.closeQuietly(os);
			}
		} else {
			InputStream is = null;
			try {
				is = new FileInputStream(idfile);
				return IOUtils.toString(is);
			} catch (Exception e) {
				LOG.error("exception when load id from {}, detail: {}",
						this._filename, ExceptionUtils.exception2detail(e));
			} finally {
				IOUtils.closeQuietly(is);
			}
		}
		return null;
	}
}
